﻿using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using Red.Controls.Shell;
using Red.Controls.Utils;

namespace Red.Launcher.Menus.Workspaces.Admin
{
    public partial class ParamDialog : RedDialog
    {
        #region Public Properties

        public static readonly DependencyProperty KeyProperty = DependencyProperty.Register( "Key", typeof( string ), typeof( ParamDialog ) );

        public string Key
        {
            get { return (string)GetValue( KeyProperty ); }
            set { SetValue( KeyProperty, value ); }
        }

        public string Value { get { return _value.Text; } }

        public bool IsValid
        {
            get
            {
                bool isValid = true;

                isValid &= Helpers.ValidateElement( _key );

                return isValid;
            }
        }

        public bool IsListeningForDeactivation { get; private set; }

        #endregion Public Properties

        #region C-Tor

        public ParamDialog()
        {
            InitializeComponent();
            WindowStartupLocation = WindowStartupLocation.Manual;
            Closing += ParamDialog_Closing;
            Activated += ParamDialog_Activated;
            Deactivated += ParamDialog_Deactivated;
            IsListeningForDeactivation = true;
        }

        #endregion C-Tor

        #region Public Methods

        public void RefreshBindingsForValidation()
        {
            Helpers.RefreshBindingValues( _key, TextBox.TextProperty );
        }

        #endregion Public Methods

        #region Event Handlers

        private void ParamDialog_Closing( object sender, CancelEventArgs e )
        {
            if ( DialogResult == true )
            {
                RefreshBindingsForValidation();

                e.Cancel = !IsValid;
            }

            if( IsListeningForDeactivation )
            {
                Deactivated -= ParamDialog_Deactivated;
                IsListeningForDeactivation = false;
            }
        }

        private void ParamDialog_Activated( object sender, EventArgs e )
        {
            _key.Focus();
        }

        private void ParamDialog_Deactivated( object sender, EventArgs e )
        {
            Close();

            Deactivated -= ParamDialog_Deactivated;
            IsListeningForDeactivation = false;
        }

        #endregion Event Handlers
    }
}
